package com.jasmine.bjstkserver.server.login;

import com.jasmine.auth.TokenManager;
import com.jasmine.auth.AuthUserService;
import com.jasmine.auth.exception.UsernameOrPasswordFaultException;
import com.jasmine.auth.model.LoginReq;
import com.jasmine.auth.model.UserInfo;
import com.jasmine.bjstkserver.core.config.annotation.AuthIgnoreLimiter;
import com.jasmine.core.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author jasmineXz
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private AuthUserService userService;

    @Autowired(required=false)
    private TokenManager tokenManager;


    /**
     * 登陆
     * @param login
     * @return
     */
    @PostMapping
    @AuthIgnoreLimiter
    public R login (@RequestBody LoginReq login) {
        UserInfo user = userService.findUserByUsername(login.getUsername(),login.getUsername());
        if (null == user || !user.getPassword().equals(login.getPassword())) {
            throw new UsernameOrPasswordFaultException();
        }
        return R.ok(tokenManager.generate(user));
    }
}
